package study.JavaAdvanced;

import java.io.*;
import java.util.Stack;

/**
 * date:2025.10.28
 * title:java序列化
 * author:fzy
 */
//java序列化：对象的状态信息  ---- 可存储或者可以传输的形式
    //就是把内存中的java对象“打包”成一串字节，这样就可以方便的进行传输
    //实现序列化必须实现java.io.Serializable接口，标记接口
public class Java_7 {
    public static void main(String[] arg){
        MyClass myClass = new MyClass();
        //序列化类，存储到object.ser
        SerializableToolClass serializableToolClass = new SerializableToolClass<MyClass>();
        //反序列化，将object.ser的类反序列化为class
        serializableToolClass.Serialization(myClass);
        MyClass myClass1 = null;
        myClass1 = (MyClass) serializableToolClass.Deserialization();
        myClass1.testIsIns();
    }
}

//实现这个接口
class MyClass implements Serializable {
     void testIsIns(){
        System.out.println("实例化成功");
    }

}

class SerializableToolClass<T>{
    //使用ObjectOutputStream进行序列化
     void Serialization(Object myClass){
        try{
            FileOutputStream fileOutputStream = new FileOutputStream("Object.ser");
            ObjectOutputStream out  = new ObjectOutputStream(fileOutputStream);
            out.writeObject(myClass);
            out.close();
            fileOutputStream.close();

        } catch (IOException e) {
          e.printStackTrace();
        }
    }

    //反序列化
    T Deserialization(){
        try{
            T obj = null;
            FileInputStream fileInputStream = new FileInputStream("Object.ser");
            ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
            obj = (T)objectInputStream.readObject();
            objectInputStream.close();
            fileInputStream.close();
            return obj;

        }catch (IOException e){
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }


        return null;
    }
}
